/**
 *@Description 清单首页
 *@Author zhangnf
 *@Date 2015-09-23
 */
var billCtrl  = new XFApp.client();
XFApp.client.prototype.bill = {
	successCode : "10000",
	successNum:0, //记录批量提交成功次数
	page : null,
	urlItems : {
		queryByPageURL : basePath+"/nt/bill/getPage",
		getBillByIdURL : basePath+"/nt/bill/getBillById", //用于展示详情页面地址 ps
		applyURL : basePath+"/nt/bill/applyAll" , // 用于批量提交 ps
		getBillByIdAll : basePath+"/nt/bill/getBillByIdAll",
		queryProgressURL: basePath+"/nt/bill/getProcessByKey"
	},

	applyAll : function(param){
		$.ajax({
			type: "POST",
			url: billCtrl.bill.urlItems.applyURL,
			data:param,
			async:false,
			success: function(msg){
				if(msg.code=="10006"){

					billCtrl.bill.successNum++;
				}
			}
		});
	},
	queryPage : function(){
		_this = this;
		if(!!_this.page){
			_this.page.page("remote",0,$('#searchForm').serializeObject());
		}else{
		_this.page = $("#page").page({
			pageSize : 10,
			currentPageIndex : Number($("#currentPageIndex").val())-1,
			remote: {
				url: _this.urlItems.queryByPageURL,
				type: 'POST',
		        params: $('#searchForm').serializeObject(), 
		        success: function (data, pageIndex) {
		        	$("#currentPageIndex").val(data.result.pageNo);
		        	if(data.code==_this.successCode){
		        		var pageResult = data.result;
		        		if(null == data 
								|| null == data.result 
									|| null == data.result.itemList
										|| data.result.itemList.length < 1){
		        			$("#page_grid").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
		        		}else{
		        			for(var index in pageResult.itemList){
		        				var element = pageResult.itemList[index];
		        				element["seqNum"]=parseInt(pageResult.pageSize)*(parseInt(pageResult.pageNo)-1)+parseInt(index)+1;
		        			}
		        			$("#page_grid").html($("#dataTmp").render(pageResult.itemList));
		        		}
		        	}else{
		        		window.webDialogUtil.alert("提示","操作失败");
		        	}
		        },
		        error : function(){
		        	window.webDialogUtil.alert("提示","操作失败");
		        }
			},
			firstBtnText : '首页',
			lastBtnText : '尾页',
			prevBtnText : '上一页',
			nextBtnText : '下一页',
			showInfo : true,
			showJump : true,
			jumpBtnText : '跳转',
			showPageSizes : true,
			infoFormat : '共{pageCount}页,{total}项'
		});
		}
	},
	dataFormat : function(timeLong){
		if(null == timeLong
				|| "" == timeLong){
			return "";
		}
		return new Date(timeLong*1000).format("yyyy-MM-dd hh:mm:ss")
	},
	
	ajaxDownload : function(){
		_this.loadingDialog = webDialogUtil.loading('正在导出，请稍后...');
		var params = {
			itemnoFuzzy : $("#itemno").val(),
			itemnameFuzzy : $("#itemname").val(),
			docketstatus : $("#docketstatus").val(),
			reqTimeStart : $("#reqTimeStart").val(),
			reqTimeEnd : $("#reqTimeEnd").val(),
			gcode : $("#gcode").val()
		}
		$.ajax({
			url:basePath+"/nt/bill/exportBillExcel",
			data:$('#searchForm').serialize(),
			type:'post',
			cache:false,
			success:function(data) {
				_this.loadingDialog.close();
				if(data.success){
					var url = basePath+"/nt/transData/download?fileName="+data.fileName;
					$("body").append("<iframe id='file_download_frame' src='" + url +"' frameborder=0 width=0 height=0 style='display:none'></iframe>");
				}else{
					window.webDialogUtil.alert("提示",data.errMsg);
				}
			},
			error : function() {
				_this.loadingDialog.close();
				window.webDialogUtil.alert("提示","操作失败");
			}
		});
	},
	batchApplyBill: function(){
		var msg1='请至少勾选一条数据';
		var msg2='仅可对待申报、申报失败的清单进行提交！';
		billCtrl.bill.successNum = 0;  //初始化成功次数
		var ids=[];
		var id = null; //后续会用id作为参数
		var docketStatus = null;
		var realId = 0;
		var total =$("input:checked").size();
		if(total<1){
			webDialogUtil.simpleAlert(msg1);
			return;
		}
		$("input:checked").each(function(i){
			id = $(this).attr("id");
			docketStatus = $(this).attr("docketStatus");
			if(docketStatus=='80'||docketStatus=='82'){
				realId++;
				ids.push(id);
			}
		});
		if(realId<1){
			webDialogUtil.simpleAlert(msg2);
			return;
		}
		var _this = this;
		webDialogUtil.simpleConfrimAlert('是否确认提交'+ids.length+'条清单？', function(){
		    $('#batchNum').html(ids.length);
			$("#modalBatchSubmitBill").modal({backdrop: 'static', keyboard: false});

			_this.loop = window.setInterval(_this.queryProgress,1000);
			$.ajax({
				type: "POST",
				url: billCtrl.bill.urlItems.getBillByIdAll,
				dataType : 'json',
				traditional:true,
				data: {ids: ids,progressKey: progressKey},
				async:true,
				success: function(msg){

					
					//billCtrl.bill.queryPage();

				},
				error : function() {
					
					//billCtrl.bill.queryPage();
				}	
			});
		});

		
	},
	loop: {},
	queryProgress: function(){
		var _this = this;
		$.ajax({
			type: "POST",
			url: billCtrl.bill.urlItems.queryProgressURL,
			dataType : 'json',
			data: {progressKey: progressKey},
			async:true,
			success: function(msg){
				billCtrl.bill.resetProgressBar(msg);
			},
			error : function() {
				billCtrl.bill.resetProgressBar();
			}	
		});
	},
	resetProgressBar: function(msg){
		if(msg){
			if(msg.doneCout > 0){
				if((msg.doneCout+msg.faildCount) >= msg.total){
					window.clearInterval(billCtrl.bill.loop);
					$('.progress .progress-bar').attr('data-transitiongoal',100).progressbar({display_text: 'fill'});
					window.setTimeout(function(){
						$("#modalBatchSubmitBill").modal('hide');
						$('.progress .progress-bar').attr('data-transitiongoal',0).progressbar({display_text: 'fill'});
						$('#doneCount').html(0);
						$('#faildCount').html(0);
						billCtrl.bill.queryPage();
					},900);
					
				}else{
					$('#doneCount').html(msg.doneCout);
					$('#faildCount').html(msg.faildCount);
					$('.progress .progress-bar').attr('data-transitiongoal',msg.donePercent).progressbar({display_text: 'fill'});
				}
				
			}
			
		}else{
			window.setTimeout(function(){
						$("#modalBatchSubmitBill").modal('hide');
						$('.progress .progress-bar').attr('data-transitiongoal',0).progressbar({display_text: 'fill'});
						$('#doneCount').html(0);
						$('#faildCount').html(0);
						billCtrl.bill.queryPage();
					},900);
		}
	},
	event : function(){
		_this = this;
		
		$("#searchButton").on("click",function(){
			billCtrl.bill.queryPage();
		});
		
		$("#exportButton").on("click",function(){
			billCtrl.bill.ajaxDownload();
		});
		/*全选绑定事件 ps*/
		$(".selectAll").on("click",function(){
			//check
			if($(".selectAll").hasClass("selected")){
				$(".check").prop("checked",false);
				$(this).removeClass("selected").addClass("unSelected");
			}
			else{
				$(".check").prop("checked",true);
				$(this).removeClass("unSelected").addClass("selected");
			}
		});
		/*/!*批量提交 ps*!/
		$("#submitAll").on("click",function(){
			billCtrl.bill.successNum = 0;  //初始化成功次数
			var id = null; //后续会用id作为参数
			var total =$("input:checked").size(); // 批量选择数目
			$("input:checked").each(function(i){
				id = $(this).attr("id");
				console.log("id:"+id);
				$.ajax({
					type: "POST",
					url: billCtrl.bill.urlItems.getBillByIdURL,
					data: "id="+id+"&docketStatus=80",
					dataType:'json',
					async:false,    //此处以为多个ajax用同一个id，为防止id影响其他，故改为同步 ps
					success: function(msg){
						//msg = eval("(" + msg + ")").result;
						msg=msg.result;
						if(msg!=null){

							//由于是批量提交，部分参数无法选择，在此用默认值代替
							var param ="docketStatus=80"+"&impExpValidate=电子商务" + "&impExpValidate=俄罗斯" + "&id=" + id + "&impExpValidate=其他" + "&tradeMode=" + msg.tradeMode + "&transferMode=" + msg.trafMode + "&loctNo=" + msg.loctNo + "&licenseNo=&country2=" + msg.country + "&destinationPort=" + msg.destinationPort + "&freight=" + msg.freight + "&freightMark=" + msg.freightMark + "&insurefeeMark=" + msg.insurefeeMark + "&wrapType=" + msg.wrapType + "&remark="
							console.log("param:"+param);
							billCtrl.bill.applyAll(param);
						}
						else {
							return;
						}

					}
				});
			});
			webDialogUtil.callbackConfrimAlert("总共提交:"+total+"票，成功:"+billCtrl.bill.successNum+"票",function(){
				history.go(0);
			});
		});*/
		/*新版批量提交，改后台处理*/

		$("#submitAll").on("click",function(){
			billCtrl.bill.batchApplyBill();
		});
		billCtrl.bill.queryPage();
	},
	loadingDialog: {}
};
$.views.converters({
	ftime : function(value) {
		return billCtrl.bill.dataFormat(value) ;
	},
	fdkstatus : function(value){
		return dksCtrl.dockerstatus.get(value);
	}
});
//form表单转对象
$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}
$(function(){
	dictCtrl.dictionary.load("billDocketStatus","docketStatusHidden");
	billCtrl.bill.event();
});